import React, { useState, useRef, useEffect, useMemo } from 'react';

interface ProgressiveImageProps {
  src: string;
  alt: string;
  className?: string;
  placeholderColor?: string;
  width?: number;
  height?: number;
  imgStyle?: React.CSSProperties;
  lazy?: boolean;
  onLoad?: () => void;
  onError?: () => void;
  priority?: boolean;
}

const ProgressiveImage: React.FC<ProgressiveImageProps> = React.memo(({
  src,
  alt,
  className = '',
  placeholderColor = '#333',
  width,
  height,
  imgStyle = {},
  lazy = true,
  onLoad,
  onError,
  priority = false
}) => {
  const [isLoaded, setIsLoaded] = useState(false);
  const [error, setError] = useState(false);
  const [shouldLoad, setShouldLoad] = useState(!lazy || priority);
  const [retryCount, setRetryCount] = useState(0);
  const imgRef = useRef<HTMLImageElement>(null);
  const observerRef = useRef<IntersectionObserver | null>(null);

  // 🚀 性能优化：使用useMemo缓存网络状态检测
  const isSlowNetwork = useMemo(() => {
    if (typeof navigator === 'undefined' || !(navigator as any).connection) return false;
    const connection = (navigator as any).connection;
    return connection.effectiveType === '2g' || connection.effectiveType === 'slow-2g';
  }, []);

  // 🚀 性能优化：改进的缓存检测逻辑
  const checkImageCache = (imageSrc: string): Promise<boolean> => {
    return new Promise((resolve) => {
      // 🚀 优化：对于慢速网络，减少等待时间
      const timeout = isSlowNetwork ? 50 : 100;
      
      const img = new Image();
      const startTime = performance.now();
      
      img.onload = () => {
        const loadTime = performance.now() - startTime;
        // 🚀 优化：根据网络状况调整缓存判断阈值
        const cacheThreshold = isSlowNetwork ? 30 : 50;
        resolve(loadTime < cacheThreshold);
      };
      
      img.onerror = () => resolve(false);
      
      // 设置超时，避免阻塞
      setTimeout(() => resolve(false), timeout);
      
      img.src = imageSrc;
    });
  };

  // 🚀 性能优化：添加错误重试机制
  const handleImageError = () => {
    if (retryCount < 2) { // 最多重试2次
      setRetryCount(prev => prev + 1);
      setError(false);
      // 延迟重试，避免立即重复请求
      setTimeout(() => {
        if (imgRef.current) {
          imgRef.current.src = src + (src.includes('?') ? '&' : '?') + `retry=${retryCount}`;
        }
      }, 1000 * (retryCount + 1)); // 指数退避
    } else {
      setError(true);
      console.error(`Failed to load image after ${retryCount} retries: ${src}`);
      if (onError) {
        onError();
      }
    }
  };

  useEffect(() => {
    setIsLoaded(false);
    setError(false);
    setRetryCount(0);
    setShouldLoad(!lazy || priority);

    // 对于非懒加载或高优先级图片，检查是否已缓存
    if (!lazy || priority) {
      checkImageCache(src).then(isCached => {
        if (isCached) {
          setIsLoaded(true);
          if (onLoad) {
            onLoad();
          }
        }
      });
      return;
    }

    // 🚀 性能优化：改进IntersectionObserver配置
    observerRef.current = new IntersectionObserver((entries) => {
      entries.forEach(async (entry) => {
        if (entry.isIntersecting) {
          setShouldLoad(true);
          
          // 在懒加载触发时也检查缓存
          const isCached = await checkImageCache(src);
          if (isCached) {
            setIsLoaded(true);
            if (onLoad) {
              onLoad();
            }
          }
          
          if (observerRef.current && imgRef.current) {
            observerRef.current.unobserve(imgRef.current);
          }
        }
      });
    }, {
      // 🚀 优化：根据网络状况调整rootMargin
      rootMargin: isSlowNetwork ? '50px 0px' : '100px 0px',
      threshold: 0.01
    });

    if (imgRef.current) {
      observerRef.current.observe(imgRef.current);
    }

    return () => {
      if (observerRef.current && imgRef.current) {
        observerRef.current.unobserve(imgRef.current);
      }
    };
  }, [src, lazy, priority, onLoad, isSlowNetwork]);

  const handleLoad = () => {
    setIsLoaded(true);
    setError(false);
    setRetryCount(0);
    if (onLoad) {
      onLoad();
    }
  };

  // 🚀 性能优化：使用useMemo缓存aspectRatio计算
  const aspectRatio = useMemo(() => {
    return width && height ? (height / width) * 100 : 0;
  }, [width, height]);

  return (
    <div
      className={`relative overflow-hidden ${className}`}
      style={{
        backgroundColor: placeholderColor,
        paddingBottom: aspectRatio ? `${aspectRatio}%` : undefined,
      }}
    >
      {error ? (
        <div className="absolute inset-0 flex items-center justify-center bg-gray-700 text-white text-xs">
          <i className="fas fa-image-slash mr-1"></i> Failed to load
        </div>
      ) : (
        <>
          {!isLoaded && shouldLoad && (
            <div className="absolute inset-0 flex items-center justify-center">
              <div className="w-6 h-6 border-2 border-pink-500 border-t-transparent rounded-full animate-spin"></div>
            </div>
          )}
          
          <img
            ref={imgRef}
            src={shouldLoad ? src : ''}
            alt={alt}
            onLoad={handleLoad}
            onError={handleImageError}
            className="w-full h-full"
            loading={priority ? "eager" : "lazy"}
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              width: '100%',
              height: '100%',
              objectFit: 'cover',
              transition: 'opacity 0.2s ease-in-out',
              opacity: isLoaded ? 1 : 0,
              objectPosition: 'center 0%',
              ...imgStyle,
            }}
          />
        </>
      )}
    </div>
  );
});

export default ProgressiveImage; 